package com.dq.service.account.impl;

import com.dq.controller.in.AccountQuery;
import com.dq.controller.in.CountAccountQuery;
import com.dq.controller.in.StaffSubscribeQuery;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.org.Org;
import com.dq.domain.subscribe.Subscribe;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.sys.user.Account;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.WxUser;
import com.dq.exception.customException.AdminException;
import com.dq.repository.BaseRepositories;
import com.dq.service.account.AccountService;
import com.dq.service.org.OrgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2020/4/13 15:44
 */
@Service
public class AccountServiceImpl extends BaseRepositories implements AccountService {
    @Autowired
    private OrgService orgService;

    @Override
    public List<Account> list(AccountQuery accountQuery) throws AdminException {
        accountQuery.format();
        Map<String, Object> query = createQuery(accountQuery);
        return dao.find(dao.query2Hql(Account.class, query), query);
    }

    @Override
    public Long accountCount(AccountQuery accountQuery) throws AdminException {
        accountQuery.format();
        Map<String, Object> query = createQuery(accountQuery);
        return dao.count(dao.count2Hql(Account.class, query), query);
    }

    /**
     * @Description: 消费次数
     * @param sql:
     * @return: int
     * @Author: @Dog_E
     * @Date: 2020/8/4 0004
     **/
    @Override
    public int accountCount(String sql) {
        Map<String,Object> maps=new HashMap<>();
        int count = Integer.parseInt(dao.count("select count(0) from Account where user_id=" + sql, maps).toString());
        return count;
    }

    @Override
    public BigDecimal countAccountByToDay(StaffSubscribeQuery countAccountQuery) throws AdminException {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT COALESCE(sum(a.price),0) price FROM `account` a  LEFT JOIN user_account_staff_user ua " +
                "on a.id = ua.account_id\n" +
                "where a.deleted = 0 ");
        if (countAccountQuery.getBeginTime() != null) {
            sql.append(" and a.create_time >=").append(countAccountQuery.getBeginTime());
        }
        if (countAccountQuery.getEndTime() != null) {
            sql.append(" and a.create_time <=").append(countAccountQuery.getEndTime());
        }
        if (countAccountQuery.getOrgId() != null) {
            sql.append(" and a.sys_dept_id =").append(countAccountQuery.getOrgId());
        }
        if (countAccountQuery.getStaffUserId() != null) {
            sql.append(" and ua.staff_user_id =").append(countAccountQuery.getStaffUserId());
        }
        sql.append(" GROUP BY a.id");
        System.out.println(sql);
        Map<String, Object> query = new HashMap<>(16);
        List<Map> list = dao.findBySql2Map(sql.toString(), query);
        BigDecimal price = BigDecimal.ZERO;
        if (list.size() > 0) {
            if (list.get(0).get("price") != null || !"".equals(list.get(0).get("price"))) {
                price = new BigDecimal(String.valueOf(list.get(0).get("price")));
            }
        }
        return price;
    }

    @Override
    public Account saveLessAccount(Subscribe subscribe, BigDecimal projectPrice, BigDecimal originalPrice, Account.AccountPayType accountPayType, BigDecimal surplusPrice, BigDecimal surplusGivePrice) throws AdminException {
        subscribe.setPrice(originalPrice);
        Subscribe save = subscribeRepository.save(subscribe);
        Account account = new Account();
        account.setUser((WxUser) subscribe.getWxUser());
        account.setSysDept(subscribe.getSysDept());
        account.setStaffUser((BossUser) subscribe.getTechnicianUser());
        account.setAccountChangeType(Account.AccountChangeType.deduct);
        account.setChangeType(Account.ChangeType.less);
        account.setPrice(originalPrice);
        account.setGivePrice(BigDecimal.ZERO);
        account.setAccountPayType(accountPayType);
        account.setSubscribe(save);
        account.setSurplusPrice(surplusPrice);
        account.setSurplusGivePrice(surplusGivePrice);
        account.setServiceProject(save.getServiceProject());
        if (originalPrice.compareTo(projectPrice) == -1) {
            account.setStatus(Account.Status.abnormal);
        } else {
            account.setStatus(Account.Status.normal);
        }
        Account save1 = accountRepository.save(account);
        return save1;
    }

    public Map<String, Object> createQuery(AccountQuery accountQuery) throws AdminException {
        //accountQuery.setOrgId(0L);
        Map<String, Object> query = accountQuery.parseMap();
        if (accountQuery.getStaffUserId() != null) {
            query.put("staffUser_id", accountQuery.getStaffUserId());
            query.remove("staffUserId");
        }

        List<Long> orgidsInList = new ArrayList<>();
        if (accountQuery.getOrgId() != null && accountQuery.getOrgId() != 0) {
            orgidsInList.add(accountQuery.getOrgId());
        } else {
            // 只显示负责门店信息
            List<Org> orgList = orgService.getListAllByUser();
            for (Org org : orgList) {
                orgidsInList.add(org.getId());
            }
        }
        if (orgidsInList.size() > 0) {
            query.put("sysDept_id" + BaseDaoImpl.inSqlStr, orgidsInList);
            query.remove("orgId");
        }
        if (accountQuery.getChangeType() != null) {

        }

        if (accountQuery.getUserCardId() != null) {
            query.put("userCard_id", accountQuery.getUserCardId());
            query.remove("userCardId");
        }
        if (accountQuery.getWxUserId() != null) {
            query.put("user_id", accountQuery.getWxUserId());
            query.remove("wxUserId");
        }
        if (StringUtils.isNotEmpty(accountQuery.getStaffUserName())) {
            query.put("staffUser_userRealcName", accountQuery.getStaffUserName());
            query.remove("staffUserName");
        }
        if (StringUtils.isNotEmpty(accountQuery.getWxUserName())) {
            query.put("user_userRealcName", accountQuery.getWxUserId());
            query.remove("wxUserName");
        }
        if (accountQuery.getBeginTime() != null) {
            query.put("createTime" + BaseDaoImpl.gteSqlStr, accountQuery.getBeginTime());
            query.remove("beginTime");
        }
        if (accountQuery.getEndTime() != null) {
            query.put("createTime" + BaseDaoImpl.lteSqlStr, accountQuery.getEndTime());
            query.remove("endTime");
        }
        if (accountQuery.getUserCartType() != null) {
            query.put("userCard_cardType", accountQuery.getUserCartType());
            query.remove("userCartType");
        }
        if (accountQuery.getOrgName() != null) {
            query.put("sysDept_simpleName", accountQuery.getOrgName());
            query.remove("orgName");
        }
        if (accountQuery.getSubscribeId() != null) {
            query.put("subscribe_id", accountQuery.getSubscribeId());
            query.remove("subscribeId");
        }
        return query;
    }
}
